package com.xujie.sportsmeeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xujie.sportsmeeting.entity.NoticeReadRecord;
import com.xujie.sportsmeeting.mapper.NoticeReadRecordMapper;
import com.xujie.sportsmeeting.service.NoticeReadRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 公告阅读记录服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NoticeReadRecordServiceImpl extends ServiceImpl<NoticeReadRecordMapper, NoticeReadRecord> implements NoticeReadRecordService {

    @Override
    @Transactional
    public boolean recordRead(Long noticeId, Long userId) {
        // 检查是否已有阅读记录
        if (hasRead(noticeId, userId)) {
            return true;
        }
        
        NoticeReadRecord record = new NoticeReadRecord();
        record.setNoticeId(noticeId);
        record.setUserId(userId);
        record.setReadTime(LocalDateTime.now());
        
        return save(record);
    }

    @Override
    @Transactional
    public boolean confirmRead(Long noticeId, Long userId) {
        // 简化为只记录阅读
        return recordRead(noticeId, userId);
    }

    @Override
    public boolean hasRead(Long noticeId, Long userId) {
        LambdaQueryWrapper<NoticeReadRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(NoticeReadRecord::getNoticeId, noticeId)
               .eq(NoticeReadRecord::getUserId, userId);
        
        return count(wrapper) > 0;
    }

    @Override
    public boolean hasConfirmed(Long noticeId, Long userId) {
        // 简化为和hasRead相同的逻辑
        return hasRead(noticeId, userId);
    }

    @Override
    public List<NoticeReadRecord> getUserReadRecords(Long userId) {
        LambdaQueryWrapper<NoticeReadRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(NoticeReadRecord::getUserId, userId)
               .orderByDesc(NoticeReadRecord::getReadTime);
        
        return list(wrapper);
    }

    @Override
    public Long getNoticeReadCount(Long noticeId) {
        LambdaQueryWrapper<NoticeReadRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(NoticeReadRecord::getNoticeId, noticeId);
        
        return count(wrapper);
    }

    @Override
    public Long getNoticeConfirmCount(Long noticeId) {
        // 简化为返回阅读数量
        return getNoticeReadCount(noticeId);
    }

    @Override
    public List<Long> getUnconfirmedUsers(Long noticeId) {
        // 简化逻辑：返回空列表，表示没有未确认用户
        return List.of();
    }

    @Override
    @Transactional
    public boolean batchConfirmRead(List<Long> noticeIds, Long userId) {
        for (Long noticeId : noticeIds) {
            confirmRead(noticeId, userId);
        }
        return true;
    }
}
